import { notificationService } from './notification'
import { taskAPI, recurringAPI } from './api'
import { authAPI } from './authAPI'

export interface ReminderSettings {
  enabled: boolean
  reminderTime: number // 提前多少分钟提醒
  dailySummary: boolean
  dailySummaryTime: string // HH:MM格式
  weeklyReview: boolean
  overdueReminders: boolean
}

const defaultReminderSettings: ReminderSettings = {
  enabled: true,
  reminderTime: 15,
  dailySummary: true,
  dailySummaryTime: '20:00',
  weeklyReview: true,
  overdueReminders: true
}

export class TaskReminderService {
  private static instance: TaskReminderService
  private settings: ReminderSettings
  private checkInterval: number | null = null
  private dailySummaryTimeout: number | null = null

  constructor() {
    this.settings = this.loadSettings()
    this.init()
  }

  static getInstance(): TaskReminderService {
    if (!TaskReminderService.instance) {
      TaskReminderService.instance = new TaskReminderService()
    }
    return TaskReminderService.instance
  }

  private init() {
    // 只有在用户已登录时才启动服务
    if (authAPI.isLoggedIn()) {
      console.log('TaskReminderService: 用户已登录，启动提醒服务')
      this.startPeriodicCheck()
      this.scheduleDailySummary()
    } else {
      console.log('TaskReminderService: 用户未登录，等待登录后启动')
    }

    // 监听页面可见性变化
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden && authAPI.isLoggedIn()) {
        // 页面重新可见且用户已登录时，立即检查一次
        this.checkTaskReminders()
      }
    })
  }

  // 启动提醒服务（用户登录后调用）
  public startService() {
    if (!authAPI.isLoggedIn()) {
      console.log('TaskReminderService: 用户未登录，无法启动服务')
      return
    }

    if (this.checkInterval) {
      console.log('TaskReminderService: 服务已在运行')
      return
    }

    console.log('TaskReminderService: 启动提醒服务')
    this.startPeriodicCheck()
    this.scheduleDailySummary()
  }

  // 停止提醒服务（用户登出时调用）
  public stopService() {
    console.log('TaskReminderService: 停止提醒服务')
    
    if (this.checkInterval) {
      clearInterval(this.checkInterval)
      this.checkInterval = null
    }

    if (this.dailySummaryTimeout) {
      clearTimeout(this.dailySummaryTimeout)
      this.dailySummaryTimeout = null
    }
  }

  private loadSettings(): ReminderSettings {
    try {
      const savedSettings = localStorage.getItem('aide_settings')
      if (savedSettings) {
        const settings = JSON.parse(savedSettings)
        return {
          enabled: settings.notifications ?? defaultReminderSettings.enabled,
          reminderTime: settings.reminderTime ?? defaultReminderSettings.reminderTime,
          dailySummary: settings.dailySummary ?? defaultReminderSettings.dailySummary,
          dailySummaryTime: settings.dailySummaryTime ?? defaultReminderSettings.dailySummaryTime,
          weeklyReview: settings.weeklyReview ?? defaultReminderSettings.weeklyReview,
          overdueReminders: settings.overdueReminders ?? defaultReminderSettings.overdueReminders
        }
      }
    } catch (error) {
      console.error('加载提醒设置失败:', error)
    }
    return defaultReminderSettings
  }

  private saveSettings() {
    try {
      const savedSettings = localStorage.getItem('aide_settings')
      const allSettings = savedSettings ? JSON.parse(savedSettings) : {}
      
      Object.assign(allSettings, {
        notifications: this.settings.enabled,
        reminderTime: this.settings.reminderTime,
        dailySummary: this.settings.dailySummary,
        dailySummaryTime: this.settings.dailySummaryTime,
        weeklyReview: this.settings.weeklyReview,
        overdueReminders: this.settings.overdueReminders
      })
      
      localStorage.setItem('aide_settings', JSON.stringify(allSettings))
    } catch (error) {
      console.error('保存提醒设置失败:', error)
    }
  }

  // 开始定期检查
  private startPeriodicCheck() {
    if (this.checkInterval) {
      clearInterval(this.checkInterval)
    }

    // 每5分钟检查一次
    this.checkInterval = setInterval(() => {
      this.checkTaskReminders()
      // 每次检查时也处理重复任务
      this.checkRecurringTasks()
    }, 5 * 60 * 1000) as unknown as number

    // 立即执行一次检查
    this.checkTaskReminders()
    this.checkRecurringTasks()
  }

  // 检查任务提醒
  private async checkTaskReminders() {
    if (!this.settings.enabled || !notificationService.canSendNotification()) {
      return
    }

    // 检查用户是否已登录
    if (!authAPI.isLoggedIn()) {
      console.log('TaskReminderService: 用户未登录，跳过任务提醒检查')
      return
    }

    try {
      const tasks = await taskAPI.getAllTasks()
      const now = new Date()
      // const reminderTimeMs = this.settings.reminderTime * 60 * 1000 // 已移到任务级别处理

      // 检查需要提醒的任务（使用每个任务的个性化提醒间隔）
      const tasksToRemind = tasks.filter((task: any) => {
        // 跳过已完成的任务
        if (task.completed) return false

        // 没有截止日期的任务不提醒
        if (!task.dueDate) return false

        const dueDate = new Date(task.dueDate)
        const timeDiff = dueDate.getTime() - now.getTime()
        
        // 使用任务的个性化提醒间隔，如果没有则使用全局设置
        const taskReminderMinutes = task.reminderMinutes || this.settings.reminderTime
        const taskReminderTimeMs = taskReminderMinutes * 60 * 1000

        // 检查是否需要提前提醒
        if (timeDiff > 0 && timeDiff <= taskReminderTimeMs) {
          return !this.wasRecentlyNotified(task.id, 'reminder')
        }

        // 检查逾期任务
        if (this.settings.overdueReminders && timeDiff < 0) {
          const hoursOverdue = Math.abs(timeDiff) / (1000 * 60 * 60)
          // 每天提醒一次逾期任务
          if (hoursOverdue >= 24 && !this.wasRecentlyNotified(task.id, 'overdue', 24 * 60 * 60 * 1000)) {
            return true
          }
        }

        return false
      })

      // 发送提醒通知
      for (const task of tasksToRemind) {
        await notificationService.sendTaskReminder({
          id: task.id,
          title: task.title,
          dueDate: task.dueDate,
          priority: task.priority
        })

        // 记录已发送通知
        this.recordNotification(task.id, task.dueDate ? 'reminder' : 'overdue')
      }

      console.log(`检查完成，发送了 ${tasksToRemind.length} 个任务提醒`)
    } catch (error) {
      console.error('检查任务提醒失败:', error)
    }
  }

  // 检查是否最近已经发送过通知
  private wasRecentlyNotified(taskId: string, type: string, timeWindow: number = 60 * 60 * 1000): boolean {
    try {
      const key = `aide_notification_${taskId}_${type}`
      const lastNotified = localStorage.getItem(key)
      if (lastNotified) {
        const lastTime = parseInt(lastNotified)
        return (Date.now() - lastTime) < timeWindow
      }
    } catch (error) {
      console.error('检查通知记录失败:', error)
    }
    return false
  }

  // 记录通知发送时间
  private recordNotification(taskId: string, type: string) {
    try {
      const key = `aide_notification_${taskId}_${type}`
      localStorage.setItem(key, Date.now().toString())
    } catch (error) {
      console.error('记录通知时间失败:', error)
    }
  }

  // 设置每日总结
  private scheduleDailySummary() {
    if (this.dailySummaryTimeout) {
      clearTimeout(this.dailySummaryTimeout)
    }

    if (!this.settings.dailySummary) {
      return
    }

    const now = new Date()
    const [hours, minutes] = this.settings.dailySummaryTime.split(':').map(Number)
    
    const summaryTime = new Date()
    summaryTime.setHours(hours, minutes, 0, 0)

    // 如果今天的时间已过，设置为明天
    if (summaryTime <= now) {
      summaryTime.setDate(summaryTime.getDate() + 1)
    }

    const timeUntilSummary = summaryTime.getTime() - now.getTime()

    this.dailySummaryTimeout = setTimeout(async () => {
      await this.sendDailySummary()
      // 设置下一天的总结
      this.scheduleDailySummary()
    }, timeUntilSummary) as unknown as number

    console.log(`每日总结已安排在: ${summaryTime.toLocaleString()}`)
  }

  // 发送每日总结
  private async sendDailySummary() {
    try {
      const tasks = await taskAPI.getAllTasks()
      const today = new Date().toISOString().split('T')[0]

      // 统计今日任务
      const todayTasks = tasks.filter((task: any) => {
        const createdDate = task.createdAt ? task.createdAt.split('T')[0] : null
        const completedToday = task.completed && task.updatedAt && task.updatedAt.split('T')[0] === today
        return createdDate === today || completedToday
      })

      const completedTasks = todayTasks.filter((task: any) => task.completed).length
      const pendingTasks = tasks.filter((task: any) => !task.completed).length
      const overdueTasks = tasks.filter((task: any) => {
        if (task.completed || !task.dueDate) return false
        return new Date(task.dueDate) < new Date()
      }).length

      await notificationService.sendDailySummary({
        completedTasks,
        pendingTasks,
        overdueTasks
      })

      console.log('每日总结已发送')
    } catch (error) {
      console.error('发送每日总结失败:', error)
    }
  }

  // 手动触发任务检查
  async triggerCheck() {
    await this.checkTaskReminders()
  }

  // 手动发送每日总结
  async triggerDailySummary() {
    await this.sendDailySummary()
  }

  // 检查并处理重复任务
  private async checkRecurringTasks() {
    // 检查用户是否已登录
    if (!authAPI.isLoggedIn()) {
      console.log('TaskReminderService: 用户未登录，跳过重复任务检查')
      return
    }

    try {
      // 触发后端重复任务处理
      await recurringAPI.triggerProcessing()
      
      // 可以在这里添加重复任务生成的通知
      const stats = await recurringAPI.getStats()
      
      if (stats.upcomingInstances > 0) {
        console.log(`发现 ${stats.upcomingInstances} 个待完成的重复任务实例`)
      }
    } catch (error) {
      console.error('检查重复任务失败:', error)
    }
  }

  // 为特定任务设置提醒
  async setTaskReminder(taskId: string, reminderTime: Date) {
    const now = new Date()
    const delay = reminderTime.getTime() - now.getTime()

    if (delay <= 0) {
      console.warn('提醒时间必须在未来')
      return
    }

    setTimeout(async () => {
      try {
        const tasks = await taskAPI.getAllTasks()
        const task = tasks.find((t: any) => t.id === taskId)
        
        if (task && !task.completed) {
          await notificationService.sendTaskReminder({
            id: task.id,
            title: task.title,
            dueDate: task.dueDate,
            priority: task.priority
          })
        }
      } catch (error) {
        console.error('发送定时提醒失败:', error)
      }
    }, delay)

    console.log(`已为任务 ${taskId} 设置提醒时间: ${reminderTime.toLocaleString()}`)
  }

  // 更新设置
  updateSettings(newSettings: Partial<ReminderSettings>) {
    const oldSettings = { ...this.settings }
    this.settings = { ...this.settings, ...newSettings }
    this.saveSettings()

    // 如果提醒设置发生变化，重新启动检查
    if (oldSettings.enabled !== this.settings.enabled || 
        oldSettings.reminderTime !== this.settings.reminderTime) {
      this.startPeriodicCheck()
    }

    // 如果每日总结设置发生变化，重新安排
    if (oldSettings.dailySummary !== this.settings.dailySummary ||
        oldSettings.dailySummaryTime !== this.settings.dailySummaryTime) {
      this.scheduleDailySummary()
    }

    // 更新通知服务设置
    notificationService.updateSettings({
      enabled: this.settings.enabled
    })
  }

  // 获取设置
  getSettings(): ReminderSettings {
    return { ...this.settings }
  }

  // 停止所有提醒
  stop() {
    if (this.checkInterval) {
      clearInterval(this.checkInterval)
      this.checkInterval = null
    }

    if (this.dailySummaryTimeout) {
      clearTimeout(this.dailySummaryTimeout)
      this.dailySummaryTimeout = null
    }
  }

  // 清理通知记录
  clearNotificationHistory() {
    try {
      const keys = Object.keys(localStorage).filter(key => 
        key.startsWith('aide_notification_')
      )
      keys.forEach(key => localStorage.removeItem(key))
      console.log(`已清理 ${keys.length} 条通知记录`)
    } catch (error) {
      console.error('清理通知记录失败:', error)
    }
  }
}

// 导出单例实例
export const taskReminderService = TaskReminderService.getInstance()
